
#include <boost/lexical_cast.hpp>
#include "ConnectionFactory.h"
#include "ConnectionControl.h"
#include "ConnectionProxy.h"
#include "RequestConnect.h"
#include "../engine/ServerDescriptor.h"
#include "../engine/DebugStream.h"

using namespace Engine;

ConnectionRef CConnectionFactory::CreateByServerDesc(string& server, ConnectionControlRef control_conn, bool bind_parent)
{
	ConnectionRef c;

	try {

		DebugStream << "CConnectionFactory - server : " << server << '\n';
		CServerDescriptor sd(server);

		if(sd.mType == SERVER_TYPE_PROXY) {
			c = ConnectionRef(new CConnectionProxy(sd, control_conn, bind_parent));
		}
		else {
			DebugStream << "Unknown server : " << server << '\n';
		}

	}
	catch(std::exception& e) {
		DebugStream << e.what() << '\n';
	}

	return c;
}

ConnectionRef CConnectionFactory::CreateByPeer(string& peer, ConnectionControlRef control_conn, bool bind_parent)
{
	RequestRef request = RequestRef(new CRequestConnect(peer));
	ResponseRef response = control_conn->SendRequest(request);
	if(!response || response->GetStatus() != RESPONSE_STATUS_OK) return ConnectionRef();

	boost::shared_ptr<CPackage::JsonDocument> doc = response->ParseContentAsJson();
	if(!doc || !doc->IsObject() || !(*doc)["server"].IsString()) return ConnectionRef();

	string server = (*doc)["server"].GetString();
	return CreateByServerDesc(server, control_conn, bind_parent);
}